package loadiconhandler

import (
	"fmt"
	"gmap-backend/internal/config"
	"gmap-backend/internal/server/vo"
	"gmap-backend/internal/util/pathutil"
	"strings"
)

type OpenbyLoadIcon struct {
}

func (owner *OpenbyLoadIcon) CanHandle(appConfig *config.AppConfig, req *vo.PathReq) (bool, any) {
	urlMatch := strings.HasPrefix(req.Path, "openby:///") || strings.HasPrefix(req.Path, "openby://")
	if !urlMatch {
		return false, nil
	}
	parts := strings.Split(strings.TrimSpace(strings.TrimPrefix(strings.TrimPrefix(req.Path, "openby:///"), "openby://")), "@@")
	if len(parts) < 2 {
		panic("openby协议格式有误")
	}
	path, opener := strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1])
	if "" == path || "" == opener {
		panic("openby协议格式有误")
	}
	return true, []string{path, opener}
}

func (owner *OpenbyLoadIcon) Handle(appConfig *config.AppConfig, req *vo.PathReq, extra any) *vo.LoadIconResp {
	parts := extra.([]string)
	path, opener := parts[0], parts[1]

	// path处理
	bigImgPath := ""
	if strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://") {
		bigImgPath = GetHttpIconUrl(appConfig, path).Url
	} else if strings.HasPrefix(path, "txt://") {
		bigImgPath = SPECIAL_PATH_TXT
	} else {
		parseResult := pathutil.ParseValidPath(path, req.CtxDir)
		if !parseResult.Succ || !parseResult.File {
			panic(fmt.Sprintf("文件不存在，无法打开：\r\n%s", path))
		}
		bigImgPath = GetFileIconUrl(appConfig, parseResult.ValidPath).Url
	}

	// opener处理
	smallImgPath := ""
	// 打开方式是固定值photo
	if "photo" == opener {
		smallImgPath = SPECIAL_PATH_PHOTO
	} else if strings.Contains(opener, "%1") {
		smallImgPath = SPECIAL_PATH_CMD
	} else {
		parseResult := pathutil.ParseValidPath(opener, "")
		if !parseResult.Succ || !parseResult.File {
			panic(fmt.Sprintf("打开方式，无法打开：\r\n%s", opener))
		}
		smallImgPath = GetFileIconUrl(appConfig, parseResult.ValidPath).Url
	}

	return &vo.LoadIconResp{
		Cascade: true,
		Url:     bigImgPath,
		Url2:    smallImgPath,
	}
}
